<script setup>
	import { ref, reactive, nextTick, } from "vue";
	import { useRouter, useRoute } from "vue-router";
	import { register, login } from '@/api/login';
  import { useI18n } from 'vue-i18n';

  const { t } = useI18n();
	const router = useRouter();
	const route = useRoute();

	const loginRef = ref(null);
	const loginRules = reactive({
		email: [{ required: true, message: t('valid.emailNotNull'), trigger: 'blur' }],
		password: [{ required: true, message: t('valid.passwordNotNull'), trigger: 'blur' }]
	})
	const loginForm = reactive({ password: "", email: "" });

	// 登录
	const toLogin = (e) => {
		loginRef.value.validate(valid => {
			if (valid) {
				login(loginForm).then(res => {
					if (res.code === 0) {
						if (res.token) {
              localStorage.setItem('aiToken', res.token);
              localStorage.setItem('email', loginForm.email);
							ElMessage({ message: t('message.loginSuccess'), type: 'success', })
							router.replace("/");
						}
					} else {
						let msg = res.msg ? `${res.msg}` : ''
						msg += msg === "" ? (res.code ? `code:${res.code}` : t('message.loginFail')) : "";
						ElMessage.error(msg)
					}
				}).catch(err => {
          console.log('err', err)
					ElMessage.error(t('message.loginFail'))
				})
			} else {
				ElMessage.error(t('message.mustInput'));
			}
		})
	}
</script>

<template>
	<div class="content">
		<el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="px-5 py-12 rounded-lg shadow w-3/4 md:w-1/3 from">
			<div class="text-xl from_title">{{$t('menu.userLogin')}}</div>
			<el-form-item class="input mt-8" prop="email">
				<el-input v-model="loginForm.email" style="width:100%" :placeholder="$t('valid.inputEmail')" />
			</el-form-item>
			<el-form-item class="input mt-8" prop="password">
				<el-input v-model="loginForm.password" style="width:100%" type="password" :placeholder="$t('valid.inputPass')" show-password />
			</el-form-item>
			<el-form-item class="input mt-8">
				<el-button @click="toLogin(ruleFormRef)" type="warning" style="width: 100%;" round>{{$t('menu.login')}}</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<style scoped>
	.input {
		width: 100%;
	}

	.from {
		/* width: 30%; */
		background-color: #fff;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.content {
		width: 100%;
		background-image: url("../../assets/img/back.png");
		background-repeat: no-repeat;
		background-color: rgba(255, 255, 255, 0.8);
		background-size: cover;
		background-position: center;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.header-login-btn {
		cursor: pointer;
	}

	.header-login-btn:hover {
		background-color: rgba(45, 84, 235, 0.1);
	}

	.header-login-btn-active {
		color: #2d54eb;
		font-weight: 500;
		border-bottom: solid 2px #2d54eb;
	}
</style>
